<template>
  <cu-layout title="套餐">
    <template #navbarExtend>
      <uv-tabs
        :active-style="{
          color: $.color.primary,
          fontWeight: 'bold',
          transform: 'scale(1.02)'
        }"
        line-width="30"
        key-name="name"
        :list="state.tabList"
        :scrollable="false"
        :current="tabActive"
        @change="tabChange"
      />
    </template>
    <view class="p-12">
      <view v-for="item in form.list" :key="item.id" class="cu-card flex-ba">
        <view class="">
          <view class="text-16 font-bold">{{ item.name }}</view>
          <view class="text-light my-7 text-13">{{ type !== 2 ? `(${item.day}天有效期，套餐用完或到期停机)` : '(与当月基础套餐失效时间同步清零)' }}</view>
          <view class="font-bold text-primary"><text class="text-16">{{ item.price }}</text><text class="">元</text></view>
        </view>
        <view class="">
          <uv-button
            :loading="loading === item.id"
            text="立即订购"
            type="primary"
            size="small"
            :color="`linear-gradient(to right, ${$.color.primary}, ${$.color.primaryDark})`"
            shape="circle"
            @click="onBuy(item.id)"
          />
        </view>
      </view>

      <view class="">
        <uv-load-more :status="form.status" />
      </view>
    </view>
  </cu-layout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import $ from '@/sheep'
const state = reactive({
  tabList: [
    { type: 1, name: '基础套餐' }
    // { type: 2, name: '加油包' }
  ]
})

const type = ref(1)

const loading = ref(0)

const tabActive = computed(() => state.tabList.findIndex(v => v.type === type.value))

const { form, resetForm } = $.useForm({
  list: [],
  page: 1,
  limit: 10,
  status: 'loadmore'
})
onLoad(async(options = {}) => {
  type.value = options.type || 1
  reload()
})

function onBuy(id) {
  loading.value = id
  $.get('/user/flowPay', {
    id,
    wx_id: uni.getStorageSync('wxId'),
    agent_id: $.store('user').agentId
  }).then(res => {
    if (!res.success) {
      return $.utils.toast(res.msg)
    }
    $.utils.wxpay(res.data.pay_config).then(payRes => {
      $.utils.toast('支付成功')
    }, () => {
      $.utils.toast('取消支付')
    })
  }).finally(() => {
    loading.value = 0
  })
}

onReachBottom(() => {
  if (form.status !== 'loadmore') return
  form.page += 1
  reload()
})

function reload() {
  if (form.status !== 'loadmore') return
  form.status = 'loading'

  $.get('/user/flowList', { type: type.value, page: form.page, limit: form.limit }).then(res => {
    if (form.page > 1) {
      form.list.push(...res.data)
    } else {
      form.list = res.data
    }
    form.status = form.limit > res.data.length ? 'nomore' : 'loadmore'
  })
}

function tabChange(data) {
  type.value = data.type
  resetForm()
  reload()
}
</script>

<style>
</style>
